<template>
  <div class="px-3 bg-white border-rounded-2xl">
    <div
      class="rounded-md"
      style="font-family: PingFang SC"
      ref="stickyElement"
      :class="{ 'is-sticky': isSticky }"
    >
      <div class="wrapper flex items-center" style="height: 60px">
        <ul class="flex text-4.5 channel-list">
          <li
            class="item mr-3.5"
            v-for="(item, index) in channelList"
            :class="{ active: item.isActive }"
            :key="item.id"
            @click="changeChannel(index)"
          >
            <div class="flex items-center hover:cursor-pointer">
              <img :src="item.icon" alt="" style="width: 21px; height: 21px" />
              <span class="ml-1 text-4">{{ item.name }}</span>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="py-5">
      <template v-if="originalList.length == 0">
        <el-empty description="description" />
      </template>
      <ul class="flex flex-wrap product-list">
        <!-- 骨架屏 -->
        <template v-if="isLoading">
          <li v-for="item in 18" class="mb-5 w-1/6 item" :key="item">
            <div class="box w-[96%] mx-auto p-1 transition-all duration-50">
              <div
                class="border-rounded-2xl overflow-hidden bg-gray-50"
                style="height: 190px"
              ></div>
              <div>
                <div class="py-2"></div>
                <div class="tags">
                  <span></span>
                </div>
                <div class="flex items-baseline justify-between">
                  <div class="flex items-baseline">
                    <span v-if="true" class="ml-1 text-sm"></span>
                    <span v-else><i></i></span>
                  </div>
                  <div class="" style="">
                    <span
                      style="width: 25px; height: 25px"
                      class="flex items-center justify-center border-rounded-2xl cursor-pointer hover:bg-red-200"
                    >
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </li>
        </template>
        <template v-else>
          <li v-for="item in productsList" class="mb-5 w-1/6 item" :key="item">
            <div class="box w-[96%] mx-auto p-1 transition-all duration-50">
              <div class="border-rounded-2xl overflow-hidden">
                <router-link :to="`/product/detail/${item.id}`" target="_blank">
                  <el-image
                    :src="item.thumbnail"
                    style="max-width: 100%; height: 100%"
                    lazy
                    @error="handleError"
                /></router-link>
              </div>
              <div>
                <div class="py-2">
                  <router-link to="/">
                    <h5 class="text-3.9 font-medium text-gray-700 text-ellipsis-2">
                      {{ item.name }}
                    </h5>
                  </router-link>
                </div>
                <div class="tags">
                  <span></span>
                </div>
                <div class="flex items-baseline justify-between">
                  <div class="flex items-baseline">
                    <Price :price="item.price" />
                    <span v-if="true" class="ml-1 text-sm">到手价</span>
                    <span v-else>销量<i>10万+</i></span>
                  </div>
                  <div class="" style="">
                    <span
                      style="width: 25px; height: 25px"
                      class="bg-red-100 flex items-center justify-center border-rounded-2xl cursor-pointer hover:bg-red-200"
                    >
                      <el-icon color="red"><Plus /> </el-icon>
                    </span>
                  </div>
                </div>
              </div>
            </div></li
        ></template>
      </ul>

      <!-- 加载更多状态提示 -->
      <div v-if="isLoadingMore" class="loading-container text-center py-5">
        <el-icon class="is-loading" size="45" color="#777373" style="margin: 0 auto">
          <Loading />
        </el-icon>
        <span class="text-sm text-gray-500 pt-2.5 block">加载中...</span>
      </div>

      <!-- 没有更多数据提示 -->
      <div v-if="!hasMore" class="no-more-data text-center py-5">
        <span class="text-sm text-gray-500">没有更多数据了</span>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue";
import { Plus, Loading } from "@element-plus/icons-vue";
import { throttle } from "@/utils/util";
import { generateProducts } from "@/mock/data/product";

const stickyElement = ref<HTMLDivElement | null>(null);
const isSticky = ref(false);

const isLoading = ref(false);
const isLoadingMore = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = 36;
const total = ref(200);

const channelList = ref<any[]>([
  {
    id: 1,
    name: "为你推荐",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280623/292024/6/16377/8116/685a772fF14a73a3e/907ab1a4b49a4ba6.png",
    isActive: true,
  },
  {
    id: 2,
    name: "心选秒杀",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280622/318439/8/11500/12943/6858e5aaF2d7f3499/36e067da0ed3d2da.png",
    isActive: false,
  },
  {
    id: 3,
    name: "潮电好物",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280623/292024/6/16377/8116/685a772fF14a73a3e/907ab1a4b49a4ba6.png",
    isActive: false,
  },
  {
    id: 4,
    name: "居家优品",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280629/311932/40/13457/9162/6862891bFf8bac966/6b33eb2f5fb62a5b.png",
    isActive: false,
  },
  {
    id: 5,
    name: "进口好物",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280623/292024/6/16377/8116/685a772fF14a73a3e/907ab1a4b49a4ba6.png",
    isActive: false,
  },
  {
    id: 6,
    name: "运动好物",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280623/292024/6/16377/8116/685a772fF14a73a3e/907ab1a4b49a4ba6.png",
    isActive: false,
  },
  {
    id: 7,
    name: "母婴好物",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280623/292024/6/16377/8116/685a772fF14a73a3e/907ab1a4b49a4ba6.png",
    isActive: false,
  },
  {
    id: 8,
    name: "汽车好物",
    count: 100,
    icon:
      "https://m.360buyimg.com/babel/jfs/t20280623/292024/6/16377/8116/685a772fF14a73a3e/907ab1a4b49a4ba6.png",
    isActive: false,
  },
]);

// 加载更多数据
const loadMoreData = async () => {
  if (isLoadingMore.value || !hasMore.value) return;

  isLoadingMore.value = true;
  currentPage.value += 1;

  // 模拟API请求延迟
  setTimeout(() => {
    const newProducts = generateProducts(pageSize);
    productsList.value = [...productsList.value, ...newProducts];

    // 模拟数据加载完毕的情况
    if (productsList.value.length >= total.value) {
      hasMore.value = false;
    }

    isLoadingMore.value = false;
  }, 1000);
};
const handleScroll = () => {
  // 获取目标元素的DOM引用
  if (!stickyElement.value) return;

  // 获取元素距离文档顶部的距离
  const elementTop = stickyElement.value.offsetTop;
  // 获取当前滚动条垂直位置（跨浏览器兼容写法）
  const scrollTop =
    window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

  // 判断是否应该吸顶
  isSticky.value = scrollTop > elementTop;

  // 检查是否滚动到底部
  const scrollHeight =
    document.documentElement.scrollHeight || document.body.scrollHeight;
  const clientHeight = window.innerHeight || document.documentElement.clientHeight;
  // 距离底部100px时触发加载
  if (scrollTop + clientHeight >= scrollHeight - 500) {
    loadMoreData();
  }
};
const handleError = (e: any) => {
  e.target.src =
    "https://img11.360buyimg.com/jdcms/s240x240_jfs/t20260821/330386/24/1628/535566/68a61250F3d200c27/de3d9595b680080d.png.avif";
};
const changeChannel = (index: number) => {
  window.scrollTo({
    top: 300,
    left: 0, // 水平方向通常为0
    behavior: "smooth", // 关键参数，启用平滑滚动
  });
  channelList.value.forEach((item) => {
    item.isActive = false;
  });
  channelList.value[index].isActive = true;

  isLoading.value = true;
  setTimeout(() => {
    productsList.value = generateProducts(pageSize);
    currentPage.value = 1;
    hasMore.value = true;
    isLoading.value = false;
  }, 750);
};
/**
 * 获取商品列表
 */
const originalList = ref<any[]>([]);
const productsList = ref<any[]>([]);

onMounted(() => {
  window.addEventListener("scroll", throttle(handleScroll, 150));
  originalList.value = generateProducts(pageSize);
  console.log(originalList.value);
  productsList.value = originalList.value.slice(0, 60);
});
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>
<style lang="scss" scoped>
.is-sticky {
  position: fixed;
  top: 89px;
  width: 100%;
  left: 0;
  z-index: 208;
  /* 可以添加一些吸附后的样式 */
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.channel-list {
  .item {
    background-color: #f5f5f5;
    border-radius: 10px;
    padding: 5px 10px;
    span {
      color: #333;
    }
    &.active {
      background-color: #f5f5f5;
      span {
        color: #ff4d4f;
        font-weight: 600;
      }
    }
    &:hover {
      span {
        color: #ff4d4f;
        font-weight: 600;
      }
    }
  }
}

.product-list {
  .item {
    .box {
      box-sizing: border-box;
      border: 2px solid #ffffff00;
      border-radius: 10px;
      &:hover {
        border-color: #ff4d4f;
        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
        transform: scale(1.05);
      }
    }
  }
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
